package com.maple.controller.user;


import com.maple.result.Result;
import com.maple.service.DishService;
import com.maple.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController("userDishController")
@RequestMapping("/user/dish")
public class DishController {
    
    @Autowired
    DishService dishService;
    @Autowired
    RedisTemplate redisTemplate;
    
    
    
    @GetMapping("/list")
    public Result list(@RequestParam String categoryId){
        //构造redis中的key，规则：dish_分类id
        String key = "dish_" + categoryId;

//        先进行Redis的查询
        List<DishVO> dishWithFlavors = (List<DishVO>) redisTemplate.opsForValue().get(key);
        if(dishWithFlavors != null && !dishWithFlavors.isEmpty()){
            return Result.success(dishWithFlavors);
        }

//        若Redis中没有，在进行数据库查询
        log.info("根据分类categor查询菜品：{}", categoryId);
        List<DishVO> list = dishService.list(categoryId);

//        并放入Redis中
        redisTemplate.opsForValue().set(key, list);

        return Result.success(list);
    }
    
    
}
